//
//  WLSettingViewController.m
//  WanLian
//
//  Created by muzhuang on 2018/8/30.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLSettingViewController.h"
#import "PersonCenterCell.h"
#import "WLUserCenterController.h"
#import "WLMessageController.h"
#import "WLloginController.h"
#import "WLMyScoreProfitController.h"
#import "WLRoutersVController.h"
#import "WLWebViewController.h"
#import "UITabBar+WLTabbarBadge.h"
#import "WLFeedbackVController.h"

@interface WLSettingViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSArray *arrImages;
    NSArray *arrTitles;
}

@property (nonatomic, strong) UITableView *tableMine;

@end

static NSString *personCell = @"personCell";

@implementation WLSettingViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSInteger unreadNum = [[NSUserDefaults standardUserDefaults] integerForKey:UNREAD_MSG_NUM];
    if (unreadNum<1) {
        [self.tabBarController.tabBar hideBadgeOnItemIndex:2];
    }
    [self.tableMine reloadData];
    [self queryUserInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    
    arrImages = @[@[@"my_profit",@"my_router",@"my_message"],@[@"my_agreement",@"my_help",@"my_feedback"],@[@"my_about"]];
    arrTitles =@[@[@"我的收益",@"我的设备",@"我的消息"],@[@"用户协议",@"帮助中心",@"意见反馈"],@[@"关于我们"]];
    _tableMine = [[UITableView alloc] init];//WithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, HEIGHT_SCREEN_WL-WL_TabBarHeight) style:UITableViewStylePlain];
    _tableMine.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tableMine.delegate = self;
    _tableMine.dataSource = self;
//    _tableMine.rowHeight = WLScaleX(58);
    
    if (@available(iOS 11.0, *)) {
        _tableMine.estimatedRowHeight = 0;
        _tableMine.estimatedSectionHeaderHeight = 0;
        _tableMine.estimatedSectionFooterHeight = 0;
    }
    [self.view addSubview:_tableMine];
    
    WLWkSelf
    [_tableMine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
//    [_tableMine registerClass:[PersonCenterCell class] forCellReuseIdentifier:personCell];
    
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, 64)];
//    headView.backgroundColor = [UIColor whiteColor];
//    _tableMine.tableHeaderView = headView;
//    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, WLScaleX(60))];
    UIButton *logOutBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, WLScaleX(50))];
//    [logOutBtn setBackgroundImage:[WLCommonTool createImageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [logOutBtn setBackgroundColor:[UIColor whiteColor]];
    logOutBtn.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:16];
    [logOutBtn setTitleColor:wlLightTextColor forState:UIControlStateNormal];
    [logOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [logOutBtn addTarget:self action:@selector(logOutAction) forControlEvents:UIControlEventTouchUpInside];
//    [footView addSubview:logOutBtn];
    _tableMine.tableFooterView = logOutBtn;
    
//    [self queryUserInfo];
}

- (void)queryUserInfo
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/query" withParamsDic:nil success:^(NSDictionary *successDict) {
        WLUserInfo *user = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:user];
        [weakSelf.tableMine reloadData];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        
    } error:^(NSError *error) {
        
    } inView:nil];
}

- (void)logOutAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您确定要退出当前账号?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        [[WLUseManager shareUser] clearUserInfo];
//        [WLCommonTool userLogout];
        WLloginController *loginController = [[WLloginController alloc] init];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:loginController] animated:NO completion:nil];
        [WLCommonTool userLogout];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UITableview - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return WLScaleX(10);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }
    return [arrTitles[section-1] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return WLScaleX(170);//WLScaleX(171);
    }
    return WLScaleX(58);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section==0)
    {
        static NSString *strPersonCell = @"personInfo";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strPersonCell];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strPersonCell];
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        for (UIView *subView in cell.contentView.subviews) {
            [subView removeFromSuperview];
        }
        cell.contentView.backgroundColor = [UIColor whiteColor];
        UIImageView *ivHead = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(20), WLScaleX(77), WLScaleX(60), WLScaleX(60))];
        ivHead.layer.cornerRadius = WLScaleX(30);
        ivHead.layer.masksToBounds = YES;
        [cell.contentView addSubview:ivHead];
        
        UILabel *labName = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(94), WLScaleX(80), WIDTH_SCREEN_WL-WLScaleX(120), WLScaleX(35))];
        labName.textColor = wlBlackColor;
        labName.font = [WLCommonTool fontTypePingFangSCMedium:20];
        [cell.contentView addSubview:labName];
        
        WLUserInfo *user = [[WLUseManager shareUser] getUserInformation];
        [ivHead sd_setImageWithURL:[NSURL URLWithString:user.headImg] placeholderImage:nil];
        labName.text = user.username;
        
        UILabel *labDetail = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(94), WLScaleX(115), 120, WLScaleX(22))];
        labDetail.textColor = wlDarkGrayColor;
        labDetail.font = [WLCommonTool fontTypePingFangSCMedium:12];
        labDetail.text = @"查看或编辑个人资料";
        [cell.contentView addSubview:labDetail];
        
        UIImageView *ivIndicator = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH_SCREEN_WL-14-8, WLScaleX(102), 9, 14)];
        ivIndicator.image = [UIImage imageNamed:@"arrow_right"];
        [cell.contentView addSubview:ivIndicator];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        NSInteger row = indexPath.row;
        PersonCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:personCell];
        if (!cell) {
            cell = [[PersonCenterCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:personCell];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.ivHead.image = [UIImage imageNamed:arrImages[section-1][row]];
        cell.labTitle.text = arrTitles[section-1][row];
        cell.labDetail.text = @"";
        cell.vMsgTip.hidden = YES;
        if (section==1)
        {
            if (row==1) {
                WLUserInfo *user = [[WLUseManager shareUser] getUserInformation];
                cell.labDetail.text = [NSString stringWithFormat:@"%ld台",(long)user.devCount];
            }
            else if (row==2)
            {
                if ([self.tabBarController.tabBar isShowBadge:2]) {
                    cell.vMsgTip.hidden = NO;
                }
            }
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    switch (indexPath.section) {
        case 0:
        {
            WLUserCenterController *userCenterVC = [[WLUserCenterController alloc] init];
            userCenterVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:userCenterVC animated:YES];
        }
            break;
        case 1:
        {
            switch (row) {
                case 0:
                    {
                        WLMyScoreProfitController *myScoreController = [[WLMyScoreProfitController alloc] init];
                        myScoreController.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:myScoreController animated:YES];
                    }
                    break;
                case 1:
                {
                    WLRoutersVController *routersVController = [[WLRoutersVController alloc] init];
                    routersVController.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:routersVController animated:YES];
                }
                    break;
                case 2:
                {
                    WLMessageController *msgController = [[WLMessageController alloc] init];
                    msgController.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:msgController animated:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 2:
        {
            if (row==0) {
                WLWebViewController *webView = [[WLWebViewController alloc] init];
//                webView.urlStr = @"http://47.75.195.106/help/agreement.html";
                webView.urlStr = [NSString stringWithFormat:@"%@/help/agreement.html",[WLCommonTool getWebHost]];
                webView.titleStr = @"用户协议";
                webView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webView animated:YES];
            }
            else if (row==1) {
                WLWebViewController *webView = [[WLWebViewController alloc] init];
//                webView.urlStr = @"http://47.75.195.106/help/helplist.html";
                webView.urlStr = [NSString stringWithFormat:@"%@/help/helplist.html",[WLCommonTool getWebHost]];
                webView.titleStr = @"帮助中心";
                webView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webView animated:YES];
            }
            else
            {
                WLFeedbackVController *feedbackController = [[WLFeedbackVController alloc] init];
                feedbackController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:feedbackController animated:YES];
            }
        }
            break;
        case 3:
        {
            if (row==0) {
                WLWebViewController *webView = [[WLWebViewController alloc] init];
//                webView.urlStr = @"http://47.75.195.106/help/aboutus.html";
                webView.urlStr = [NSString stringWithFormat:@"%@/help/aboutus.html",[WLCommonTool getWebHost]];
                webView.titleStr = @"关于我们";
                webView.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webView animated:YES];
            }
            else
            {
            }
        }
            break;
            
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
